package org.jxc.service;

import java.util.Date;

import org.hibernate.SessionFactory;
import org.jxc.constants.JXCString;
import org.jxc.dao.SalesBackOrderDAO;
import org.jxc.domain.SalesBackOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.team4.dao.DAOFactory;
import org.team4.domain.Users;
import org.team4.exception.CRUDException;
import org.team4.service.IService;
import org.team4.util.LoginBean;
import org.team4.vo.Page;

public class SalesBackOrderService implements IService {

	private SalesBackOrderDAO salesBackOrderDAO;

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		salesBackOrderDAO = (SalesBackOrderDAO) DAOFactory.getDAO(
				sessionFactory, SalesBackOrderDAO.class);
	}

	public Page<SalesBackOrder> listPagination(Page<SalesBackOrder> page)
			throws CRUDException {
		Users user = LoginBean.getLoginBean().getUser();
		if (user.getDepartment().getManager().getId().equals(user.getId()) ) {
			return salesBackOrderDAO.pagination(page,
					"from SalesBackOrder where deleteFlag='0'", "createTime desc");
		}else {
			return salesBackOrderDAO.pagination(page,
					"from SalesBackOrder where deleteFlag='0'" +
					"  and creator.id= '"+ user.getId() +"'", "createTime desc");
		}
		
	}

	/**
	 * 根据id查询商品
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public SalesBackOrder findById(String id) throws Exception {
		SalesBackOrder sbo = salesBackOrderDAO.get(id);
		return sbo;
	}

	/**
	 * 新建销售订单
	 * 
	 * @param SaleOrder
	 * @throws CRUDException
	 */
	public void saveSaleBackOrder(SalesBackOrder sbo) throws CRUDException {
		sbo.setDeleteFlag("0");
		sbo.setAuditState(JXCString.NOTAPPLY);
		sbo.setAuditor(LoginBean.getLoginBean().getUser().getDepartment()
				.getManager());
		sbo.setCreateTime(new Date());
		sbo.setCreator(LoginBean.getLoginBean().getUser());
		salesBackOrderDAO.save(sbo);
	}

	/**
	 * 修改商品信息
	 * 
	 * @param SaleOrder
	 * @throws CRUDException
	 */
	public void updateSalesBackOrder(SalesBackOrder sbo) throws CRUDException {
		SalesBackOrder old = salesBackOrderDAO.get(sbo.getId());
		old.setBackDate(sbo.getBackDate());
		old.setOperator(sbo.getAuditor());
		old.setReason(sbo.getReason());
		old.setEditor(LoginBean.getLoginBean().getUser());
		old.setEditTime(new Date());
		old.setStoreState(sbo.getStoreState());
		old.setAuditState(sbo.getAuditState());
		salesBackOrderDAO.update(old);
	}

	/**
	 * 批量删除销售订单
	 * 
	 * @param idList
	 * @return
	 * @throws CRUDException
	 */
	public void deleteSalesBackOrder(String id) throws CRUDException {
		SalesBackOrder sbo = salesBackOrderDAO.get(id);
		sbo.setDeleteFlag("1");
		salesBackOrderDAO.delete(sbo);
	}
}
